/**
 * 
 */
package br.com.buscapecas.servlet;

import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * @author PH04793
 */
public class ControllerServlet extends HttpServlet implements Serializable {

    private static final long serialVersionUID = 5450728498525573487L;

    protected Logger log;
    protected Logger logDefault;
    
    /**
     * 
     * @author Maikon Rafael da Rocha
     * @since 25/10/2010 17:12:58
     * @see javax.servlet.GenericServlet#init()
     */
    @Override
    public void init() throws ServletException {
        logDefault = Logger.getLogger(this.getClass());
        super.init();
    }
    
    /*
     * (non-Javadoc)
     * @see
     * javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest
     * , javax.servlet.http.HttpServletResponse)
     */
    @SuppressWarnings("unchecked")
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        Date d = new Date();
        try {
//            this.logDefault.info(d+ "INICIO - ControllerServlet");
            String[] urlFragments = request.getPathInfo().replaceFirst("\\.do","").split("/");
            String actionName = urlFragments[urlFragments.length - 1];
            Class clazz = Class.forName("br.com.posthaus.monteseulook.controller.action."
                                        + request.getServletPath().replaceFirst("/",
                                                                                ""));
            Object action = clazz.newInstance();
            Method method = clazz.getDeclaredMethod(actionName,
                                                    new Class[]{
                                                                HttpServletRequest.class,
                                                                HttpServletResponse.class,
                                                                ServletContext.class});
            method.invoke(action,
                          new Object[]{request, response, this.getServletContext()});
        } catch (InvocationTargetException e) {
            e.printStackTrace();
            this.log.fatal(e.getMessage(), e);
            request.getSession().removeAttribute("linkAtivo");
            this.getServletContext().getRequestDispatcher("/htdocs/erro.jsp").forward(request, response);
        } catch (Exception e) {
            this.log.fatal(e.getMessage(), e);
        }/* finally {
            this.logDefault.info(d+ "FIM - ControllerServlet");            
        }*/
    }

}
